<?
include "../db_config.php";
include "Database.class.php";
include_once "snoopy/Snoopy.class.php";
include_once "util.php";

function toTimeStamp($date)
{
	//$d2 = split(" " , $date);
	//$d = split(":", $d2[1]);
	$d = split(":", $date);
	$month = date("n");
	$day = date("j");
	$year = date("Y");
	return mktime($d[0], $d[1], $d[2], $month, $day, $year);
}
$db = new Database($host_name, $user_name, $db_password, $db_name);
$db->connect();
$sql = "select * from subway_log where status is not null order by id desc limit 1";
$d = $db->query_first($sql);
$t = strtotime($d[logtime]);
//다른 클라이언트에서 업데이트 중이고
//업데이트 시간이 5초 미만이면
if($d[status] == 'updating')
{
	$d = array();
	$d[ip] = $_SERVER['REMOTE_ADDR'];
	$d[UA] = $_SERVER['HTTP_USER_AGENT'];

	//db에 로그만 추가하고 아무것도 하지 않음
	$db->query_insert("subway_log", $d);
	//3000 ms 후에 재시도할 것
	echo "3000";
	exit(0);
}
$d = array();
$d[ip] = $_SERVER['REMOTE_ADDR'];
$s_time = microtime(true);
$d[status] = "updating";
$d[demandTime] = $s_time;
$d[UA] = $_SERVER['HTTP_USER_AGENT'];
$log_id = $db->query_insert("subway_log", $d);

$line = $HTTP_GET_VARS['line'];
$updown = $HTTP_GET_VARS['updown'];

$line = 2;
$updown = 2;

$line = null;
$updown = null;


$day = date("D");
if($day == "Sat")
	$week = 2;
else if($day == "Sun")
	$week = 3;
else
	$week = 1;

$totalNo = 0;

//echo "{\"Points\":[";
$updates = array();

function printInfo($line, $updown)
{
	global $db, $week, $totalNo, $updates;
	$i = 0;

	$st = "startTime".$week;
	$ed = "endTime".$week;

	//$time = date('H:i:s');
	$time = getTime();
	//$time = '14:41:00'; 

	$currentTime = time();
	$sql = "select * from trainInfo where $st <= '$time' and $ed >= '$time'";
	if($line != null)
		$sql .= " and line = '$line'";
	if($updown != null)
		$sql .= " and updown='$updown' ";

	//해당 열차 정보를 꺼내온다
	$rows = $db->fetch_all_array($sql);

	foreach($rows as $data)
	{
		$trainId = $data[trainId];
		//$week = $data[week];
		$updown = $data[updown];
		//남은 시간(초)
		$remain = 0;

		//정차해 있는 역이 있는지 검색
		$sql = "select * from stationTimeTable where trainId =
		'$trainId' and line = '$line' and week = '$week' and updown = '$updown'
		and arrivalTime <= '$time' and departTime >= '$time' limit 1";

		$update_data = array();

		$d3 = $db->query_first($sql);
		//열차가 정차해 있는 경우
		if($d3 != null)
		{
			//역정보 꺼내기
			$sql = "select * from stationInfo where stationId =
			'".$d3[stationId]."'";
			$s1 = $db->query_first($sql);
			$lat = $s1[lat];
			$lng = $s1[lng];
			$t1 = toTimeStamp($d3[departTime]);
			$remain = $currentTime - $t1;

			$update_data[lastStationId] = $s1[stationId];
			$update_data[nextStationId] = $s1[stationId];
		}
		//열차가 움직이고 있는 경우
		else
		{

			//직전역
			$sql = "select * from stationTimeTable where trainId =
			'$trainId' and line = '$line' and week = '$week' and updown = '$updown'
			and departTime != '도착'
			and departTime < '$time' order by departTime desc limit 1";
			$d1 = $db->query_first($sql);
			if($d1 == null)
			{
					continue;
			}

			//역정보 꺼내기
			$sql = "select * from stationInfo where stationId = ".$d1[stationId];
			$s1 = $db->query_first($sql);

			//도착 예정역
			$sql = "select * from stationTimeTable where trainId =
			'$trainId' and line = '$line' and week = '$week' and updown = '$updown'
			and arrivalTime != '출발'
			and arrivalTime > '$time' order by arrivalTime limit 1";
			$d2 = $db->query_first($sql);

			//버그있음
			//마지막역이 timetable에 없음
			if($d2 == null)
			{
					continue;
			}

			$sql = "select * from stationInfo where stationId = ".$d2[stationId];
			$s2 = $db->query_first($sql);

			$t1 = toTimeStamp($d1[departTime]);
			$t2 = toTimeStamp($d2[arrivalTime]);
			$remain = $t2 - $currentTime;
			$ratio = 1.0 - ($t2 - $currentTime) / ($t2-$t1); 
			$lat = $s1[lat] + ($s2[lat] - $s1[lat]) * $ratio;
			$lng = $s1[lng] + ($s2[lng] - $s1[lng]) * $ratio;

			$update_data[lastStationId] = $s1[stationId];
			$update_data[nextStationId] = $s2[stationId];

		}

		$update_data[lat] = $lat;
		$update_data[lng] = $lng;
		$update_data[remain] = $remain;
		$update_data[running] = 1;
		$update_data[tid] = $data[tid];
		$updates[$totalNo++] = $update_data;

		//$db->query_update('trainInfo', $update_data, "tid = ".$data[tid]);

		//echo "{\"lat\":$lat,\"lng\":$lng,".
		//"\"trainId\":\"$trainId\",\"remainTime\":$remain,".
		//"\"line\":\"$line\"},\n";
		//echo $s1[stationName] . " " . $s2[stationName] . "<BR>\n";
		$i++;
	}
}

$sql = "select distinct line from trainInfo";
$rows = $db->fetch_all_array($sql);
foreach($rows as $data)
{
	for($j = 1; $j <= 2; $j++)
	{
		printInfo($data[line], $j);
	}
}


$u_s_time = microtime(true);
$sql = "UPDATE trainInfo SET running =0";
$db->query($sql);

foreach($updates as $d)
{
	$db->query_update('trainInfo', $d, "tid = ".$d[tid]);
}
$u_e_time = microtime(true);
$update_time = ($u_e_time - $u_s_time) * 1000.0;

//echo "]}";

//echo microtime(true);
//echo "<BR>";

$e_time = microtime(true);
$during = $e_time - $s_time;
$d = array();
$d[loading] = $during*1000.0;
$d[param] = $_SERVER[QUERY_STRING];
$d[totalNo] = $totalNo;
$d[updateTime] = $update_time;
$d[finishTime] = $e_time;
$d[ip] = $_SERVER['REMOTE_ADDR'];
$d[status] = "finish";
//$db->query_insert("subway_log", $d);
$db->query_update('subway_log', $d, "id = $log_id");
//echo $e_time . "<BR>";

$response = 1000 - $d[loading];
if($response < 0)
{
	$response = 0;
}
echo intval($response);

$no = $db->query_first("select COUNT(*) from subway_log");
//로그는 1000개만 관리하자
if($no['COUNT(*)'] > 1000)
{
	$sql = "delete from subway_log order by id limit 1";
	$db->query($sql);
}
$db->close();
//$today = date("H:i:s");     
//echo "$today<BR>\n$during sec";
?>
